const express = require('express');
const db = require('../db');  // 引入数据库连接对象
const router = express.Router();

router.get('/getWrongQuestions', (req, res) => {
    const { studentId, chapter, knowledge, keyword, startDate, endDate, page, pageSize } = req.query;

    // 基础查询语句，JOIN 连接 `wrong_question_set`, `student` 和 `question` 表
    let query = `
        SELECT 
            wqs.record_id,
            wqs.student_id, 
            wqs.date_added,
            wqs.review_date,
            wqs.comments,
            wqs.account,
            q.question_id,
            q.content AS questionContent,
            q.option AS questionOptions,
            q.answer AS questionAnswer,
            q.question_type,
            q.analysis,
            q.question_difficulty,
            q.knowledge_point
        FROM wrong_question_set wqs
        JOIN question q ON wqs.question_id = q.question_id
        WHERE wqs.student_id = ?
    `;

    const queryParams = [studentId];

    // 根据筛选条件拼接 SQL 查询
    if (chapter) query += ` AND q.chapter_id = ?`;
    if (knowledge) query += ` AND q.knowledge_point = ?`;
    if (keyword) query += ` AND q.content LIKE ?`;
    if (startDate && endDate) query += ` AND wqs.date_added BETWEEN ? AND ?`;

    // 分页处理
    const offset = (parseInt(page) - 1) * parseInt(pageSize);
    query += ` LIMIT ?, ?`;
    queryParams.push(offset, parseInt(pageSize));

    // 将筛选条件值添加到查询参数中
    if (chapter) queryParams.push(chapter);
    if (knowledge) queryParams.push(knowledge);
    if (keyword) queryParams.push(`%${keyword}%`);
    if (startDate && endDate) queryParams.push(startDate, endDate);

    // 执行查询
    db.query(query, queryParams, (err, results) => {
        if (err) {
            return res.status(500).json({ message: '数据库查询失败', error: err });
        }
        console.log(results)
        // 返回查询结果
        res.json({ data: results });
    });
});


// 删除错题
router.delete('/deleteWrongQuestion', (req, res) => {
    const { id } = req.body;
    const query = 'DELETE FROM wrong_questions WHERE id = ?';

    db.query(query, [id], (err, results) => {
        if (err) {
            return res.status(500).json({ message: '删除失败' });
        }
        res.json({ message: '删除成功' });
    });
});

// 批量删除错题
router.post('/batchDeleteWrongQuestions', (req, res) => {
    const { ids } = req.body;  // 接收一个数组的ID

    const query = `DELETE FROM wrong_questions WHERE id IN (?)`;
    db.query(query, [ids], (err, results) => {
        if (err) {
            return res.status(500).json({ message: '批量删除失败' });
        }
        res.json({ message: '批量删除成功' });
    });
});

// 导出错题（返回题目列表）
router.get('/exportWrongQuestions', (req, res) => {
    const query = 'SELECT question FROM wrong_questions';

    db.query(query, (err, results) => {
        if (err) {
            return res.status(500).json({ message: '导出失败' });
        }
        res.json({ data: results });
    });
});

module.exports = router;
